<?php

/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not 
 *  exist, see <http://www.gnu.org/licenses/>.
 * 
 * $LastChangedDate: 2008-12-05 23:44:23 +0100 (Fri, 05 Dec 2008) $
 * $Rev: 321 $
 * $Author: gavinspearhead $
 * $Id: show_functions.php 321 2008-12-05 22:44:23Z gavinspearhead $
 */

if (!defined('ORIGINAL_PAGE')) die('This file cannot be accessed directly.');

$pathsf = realpath(dirname(__FILE__));

require_once "$pathsf/../functions/autoincludes.php";
require_once "$pathsf/../functions/urdversion.php";
require_once "$pathsf/../functions/defines.php";
require_once "$pathsf/../config.php";
require_once "$pathsf/../functions/functions.php";
require_once "$pathsf/urdd_command.php";
require_once "$pathsf/urdd_protocol.php";
require_once "$pathsf/urdd_error.php";
require_once "$pathsf/../functions/urd_log.php";


function show_time()
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$status = date('r') . "\n";
	return $status;
}


function do_show_servers(DatabaseConnection $db, server_data $server_data)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$resp = "Servers:\n";
	$c = 1;
	$servers = $server_data->get_servers($db);
	foreach($servers as $s) {
		$pref = $s['preferred'] ? '*' : ' ';
		$id = $s['id'];
		$hostname = $s['hostname'];
		$port = $s['port'];
		$maxt = $s['max_threads']; 
		$freet = $s['free_threads'];
		$posting = $s['posting'] ? 'posting' : 'noposting';
		$prio = $s['priority'];
		$enabled = ($prio == 0) ? 'disabled' : 'enabled';
		$resp .= " #$c. id: $id h:$hostname:$port p:$prio max:$maxt free:$freet $enabled $posting $pref\n";
		$c++;
	}
	return $resp;
}


function show_uptime()
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	global $start_time;
	$uptime = time () - $start_time;
	$sec = $uptime % 60;
	$min = ($uptime / 60) % 60;
	$hrs = ($uptime / 3600) % 24;
	$days = (int) ($uptime / (3600 * 24));
	$status = sprintf("%u days %u:%02u:%02u\n", $days, $hrs, $min, $sec);
	return $status;
}


function do_show_queue (server_data $servers)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$c = 1;
	$resp = "Queue:\n";
	$actions = $servers->get_queue();
	foreach ($actions as $q) {
		$stat = $q['pause']?'paused':'active';
		$qt = microtime(TRUE) -($q['queue_time']);
		$resp .= " #$c. id:{$q['id']} u:{$q['username']} p:{$q['priority']} cmd:{$q['command']} {$q['args']} $stat qt:$qt\n";
		$c++;
	}
	return $resp;
}


function do_show_newsgroups(DatabaseConnection $db, $subscribed)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$like = ($subscribed)? ' AND "active"=\'' . NG_SUBSCRIBED . "'" : '';

	$query = 'SELECT * ' .
		 "FROM groups WHERE 1=1 $like ORDER BY \"name\"";

	$res = $db->execute_query($query);
	if ($res === FALSE) 
		return FALSE;
	$c = 1;
	$resp = "Newsgroups:\n";
	foreach ($res as $row) {
		$name = $row['name'];
		$expire = $row['expire'];
		$postcount = $row['postcount'];
		$lastupdated = $row['last_updated'];
		$id = $row['ID'];
		$resp .= " #$c id:$id exp:$expire cnt:$postcount lu:$lastupdated ng:$name\n";
		$c++;
	}
	return $resp;
}


function do_show_feeds( DatabaseConnection $db)
{
	$sql = "SELECT * FROM rss_urls ORDER BY \"name\"";
	$res = $db->execute_query($sql);
	if ($res === FALSE) 
		return FALSE;
	$c = 1;
	$resp = "RSS Feeds:\n";
	foreach ($res as $row) {
		$name = $row['name'];
		$expire = $row['expire'];
		$postcount = $row['feedcount'];
		$lastupdated = $row['last_updated'];
		$url = $row['url'];
		$id = $row['id'];
		$resp .= " #$c id:$id exp:$expire cnt:$postcount lu:$lastupdated ng:$name url:$url\n";
		$c++;
	}
	return $resp;
}


function do_show_users(conn_list $conn_list)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$c = 1;
	$resp = "Users:\n";
	$users = $conn_list->get_usernames();
	foreach ($users as $u) {
		$resp .= " #$c.  $u\n";
		$c++;
	}
	return $resp;
}


function do_show_threads(server_data $servers)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$c = 1;
	$resp = 'Threads:' . "\n";
	$threads = $servers->get_threads(); // better solution needed TODO
	foreach ($threads as $t) {
		$server = $t['server'];
		$stat = $t['paused']?'paused':'active';
		$qt = microtime(TRUE) - ($t['queue_time']);
		$st = microtime(TRUE) - ($t['start_time']);
		$resp .= " #$c.  id:{$t['id']} pid:{$t['pid']} u:{$t['username']} s:{$server}"
			.  " cmd:{$t['command']} {$t['args']} $stat qt:$qt st:$st\n";
		$c++;
	}
	return $resp;
}


function do_show_jobs(server_data $servers)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$c = 1;
	$resp = "Jobs:\n";
	$jobs = $servers->get_jobs();
	foreach($jobs as $j) {
		$time = strftime('%D %T',$j['time']);
		$recur = $j['recurrence'];
		if ($recur !== NULL)
			$rec_str = "(repeat every $recur sec) ";
		else 
			$rec_str = '';
		$resp .= " #$c.  @ $time $rec_str{$j['id']} u:{$j['username']} cmd:{$j['command']} {$j['args']}\n";
		$c++;
	}
	return $resp;
}


function do_show_config()
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	global $config;
	$resp = '';
	foreach ($config as $elem => $value) {
		$v = is_bool($value)? ($value?'TRUE':'FALSE') : $value;
		$resp .= "$elem : $v\n";
	}
	return $resp;
}


function do_show_version()
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$ver = get_version();
	$resp = "Version: $ver\n";
	return $resp;
}


function do_show_load()
{
	$load = sys_getloadavg();
	$resp = "Load:\n";
	$resp .= "1' {$load[0]}\n";
    $resp .= "5'  {$load[1]}\n";
    $resp .= "15'  {$load[2]}\n";
    return $resp;
}


function do_show_tests()
{
	global $test_results;
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$resp = "Test results:\n";
	$resp .= $test_results->get_all_as_string();
	return $resp;
}


function do_show(array $arg_list, conn_list $conn_list, server_data $servers, DatabaseConnection $db)
{
	echo_debug_function(DEBUG_SERVER, __FUNCTION__);
	$resp = '';
	foreach($arg_list as $arg) {
		switch (strtolower($arg)) {
		case 'feeds':
			$resp .= do_show_feeds($db);
			break;
		case 'version':
			$resp .= do_show_version();
			break;
		case 'all':
			$resp .= do_show_threads($servers);
			$resp .= do_show_queue($servers);
			$resp .= do_show_jobs($servers);
			$resp .= do_show_users($conn_list);
			$resp .= do_show_servers($db, $servers);
			break;
		case 'users':
			$resp .= do_show_users($conn_list);
			break;
		case 'queue':
			$resp .= do_show_queue($servers);
			break;
		case 'threads':
			$resp .= do_show_threads($servers);
			break;
		case 'jobs':
			$resp .= do_show_jobs($servers);
			break;
		case 'servers':
			$resp .= do_show_servers($db, $servers);
			break;
		case 'newsgroups':
			$resp .= do_show_newsgroups($db, FALSE);
			break 2;
			break;
		case 'subscribed':
			$resp .= do_show_newsgroups($db, TRUE);
			break 2;
		case 'config':
			$resp .= do_show_config();
			break 2;
		case 'tests':
			$resp .= do_show_tests();
			break 2;
		case 'load':
			$resp .= do_show_load();
			break;
		default :
			write_log('Error_unknown action');
			return FALSE;
			break;
		}
	}
	return $resp;
}


?>
